﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Medianamik.Core;
using Medianamik.Core.Sugar;

namespace Medianamik.UI.Controls
{
    public class MedianamikLink : TreeView
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            CurrentItemValue = "root";
            NeedChildren += MedianamikLink_NeedChildren;
            NeedSelfAndParents += MedianamikLink_NeedSelfAndParents;
            OnClientDoubleClick = "insertLink";
            Skin = Skins.DEFAULT_SKIN;
            EnableEmbeddedSkins = Skins.DEFAULT_USE_EMBEDDED_SKIN;
        }

        void MedianamikLink_NeedSelfAndParents(object sender, NeedSelfAndParentsEventArgs e)
        {
            e.Items.Add(new TreeItem("root", "root", null, null, true, true, int.MinValue, false));
        }

        private List<Node> _rootNodes;
        public List<Node> RootNodes
        {
            get
            {
                if (_rootNodes == null)
                {
                    _rootNodes = NodeManager.GetChildNodes(CurrentModule.ID);
                    _rootNodes.Sort((n1, n2) => n1.LongPosition.CompareTo(n2.LongPosition));
                }
                return _rootNodes;
            }
        }

        private MedianamikModule _currentModule;
        public MedianamikModule CurrentModule
        {
            get
            {
                if (_currentModule == null)
                {
                    int i = 1;

                    while (!Page.Request.Url.Segments.ElementAt(i - 1).Equals("medianamik/", StringComparison.OrdinalIgnoreCase))
                    {
                        i++;
                    }

                    string alias = "";

                    if (i < Page.Request.Url.Segments.Length - 1)
                    {
                        alias = Page.Request.Url.Segments.ElementAt(i);
                    }

                    if (alias.Length > 1)
                    {
                        _currentModule = ConfigManager.GetModuleByAlias(alias.Substring(0, alias.Length - 1));
                    }

                    if (_currentModule == null)
                    {
                        throw new Exception("Module not found.");
                    }
                }

                return _currentModule;
            }
        }

        void MedianamikLink_NeedChildren(object sender, NeedChildrenEventArgs e)
        {
            Guid g;
            if (!StringHelper.IsGuid(e.ParentValue, out g))
            {
                //Il s'agit d'une demande pour les noeuds racine
                e.ChildNodes.AddRange(
                    RootNodes.Select(n => (ITreeItem)new TreeItem(n.DisplayName, n.ID.ToString(), null, n.NodeType.IconPath, n.HasChildren, true, n.Depth, n.NodeType.GetAllProperties().Any(p => String.Compare(p.Name, "url", true) == 0))));
            }
            else
            {

                var node = NodeManager.GetNode(g);
                var nodes = NodeManager.GetChildNodes(node.ID, false, 1);
                nodes.Sort((n1, n2) => n1.LongPosition.CompareTo(n2.LongPosition));

                e.ChildNodes.AddRange(nodes
                    .Select(p => (ITreeItem)new TreeItem(p.DisplayName, p.ID.ToString(), null, p.NodeType.IconPath, p.HasChildren, p.CanHaveChildNodes, p.Depth, p.NodeType.GetAllProperties().Any(n => String.Compare(n.Name, "url", true) == 0))));

            }
        }

        protected override void Render(HtmlTextWriter writer)
        {

            const string script = @"
                <script type=""text/javascript"">
                    function getRadWindow(){
                        if (window.radWindow){return window.radWindow;}
                        if (window.frameElement && window.frameElement.radWindow){return window.frameElement.radWindow;}
                                return null;
                    }
                    function initDialog(){
                        var clientParameters = getRadWindow().ClientParameters;
                    }
                    if (window.attachEvent){window.attachEvent(""onload"", initDialog);}
                    else if (window.addEventListener){window.addEventListener(""load"", initDialog, false);}
                    
                    function insertLink(sender, eventArgs){
                        var node = eventArgs.get_node();
                        if (node.get_category() == ""Disabled"") {
                            
                        }
                        else {
                            var closeArgument = {}; 
                            closeArgument.href = "".@"" + node.get_value() + "".@"";
                            closeArgument.text = node.get_text();
                            closeArgument.nodeid = node.get_value();
                            getRadWindow().close(closeArgument);
                        }
                    }
                </script>";

            writer.Write(script);
            base.Render(writer);
        }
    }
}
